﻿<cfcomponent displayname="Preference" hint="Preference" extends="Controller" output="false">

	<cffunction name="init" access="public" hint="init" description="init">
		
		<cfscript>
			
			filters(through="isLoggedIn");
			
			flashInsert(menu="Preference");
			
			return this;
			
		</cfscript>
		
	</cffunction>
	
	<cffunction name="changePassword" access="public" hint="change password" description="change password">
		
		<cfscript>
			
			if (not Len(Trim(params.currentPassword))) {
				flashInsert(error="Required: Current Password");
				redirectTo(controller="Preference");
			}
			
			if (not Len(Trim(params.newPassword))) {
				flashInsert(error="Required: New Password");
				redirectTo(controller="Preference");
			}
			
			if (not Len(Trim(params.confirmNewPassword))) {
				flashInsert(error="Required: Confirm New Password")
				redirectTo(controller="Preference");
			}
			
			if (compare(params.newPassword, params.confirmNewPassword) neq 0) {
				flashInsert(error="New Password not equal to Confirm New Password");
				redirectTo(controller="Preference");
			}
			
			user = model("user").findOne(where="username='#GetAuthUser()#'");
			
			if (IsObject(user)) {
				
				// test supplied password and stored password
				if (compare(shaHash(params.currentPassword), user.userpassword) eq 0) {
					
					// can't use current password as new password
					if (compare(shaHash(params.newPassword), user.userpassword) eq 0) {
						flashInsert(error="Please use another password");
						redirectTo(controller="Preference");
					}
					else {
						user.userPassword = shaHash(params.newPassword);
						user.save();
					}
					
				}
				else {
					flashInsert(error="Wrong Current Password");
					redirectTo(controller="Preference");
				}
			}
			else {
				flashInsert(error="Failed to change password")
				redirectTo(controller="Preference");
			}
			
			
			flashInsert(info="Successfully change password");
			redirectTo(controller="Preference");
			
		</cfscript>
		
	</cffunction>   
	
</cfcomponent>